package com.personal.ifanya.domain;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.personal.ifanya.application.dto.VoteDTO;
import com.personal.ifanya.infrastructure.dal.dao.VoteItemDAO;
import com.personal.ifanya.infrastructure.dal.entity.VoteItemDO;

@Component
public class VoteBiz {

	@Autowired
	private VoteItemDAO voteItemDAO;
	
	
 	public List<VoteDTO> getAll()
 	{
 		List<VoteDTO> result = new ArrayList<VoteDTO>();
 		
 		List<VoteItemDO> dos = voteItemDAO.selectAll();
 		
 		if(dos!=null && dos.size()>0)
 		{
 			int sum = 0;
 			for(VoteItemDO item : dos)
 			{
 			   sum +=item.getScore();
 			}
 			
 			int i=0;
 			int sum_percent=0;
 			for( ; i < dos.size()-1; i++)
 			{
 				VoteItemDO temp = dos.get(i);
 				VoteDTO dto = new VoteDTO();
 				dto.setDesc(temp.getDesc());
 				int percent = (int)(new Double((temp.getScore()*100))/new Double(sum));
 				sum_percent+=percent;
 				dto.setPercent(percent+"%");
 				dto.setValue(temp.getValue()+"");
 				result.add(dto);
 			}
 			VoteItemDO temp = dos.get(i);
			VoteDTO dto = new VoteDTO();
			int percent = 100-sum_percent;
			dto.setDesc(temp.getDesc());
			dto.setPercent(percent+"%");
			dto.setValue(temp.getValue()+"");
			result.add(dto);
 
 		}
 		 
 		
 		return result;
 	}
	
 	
 	public boolean addVote(int whichvote, int value)
	{
		if( voteItemDAO.addVote(whichvote, value) > 0)
		{
			return true;
		}
		else
			return false;
	}
	
}
